package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysUserInfo;
import com.itheima.ydd.entity.Role;
import com.itheima.ydd.entity.User;
import com.itheima.ydd.service.RoleService;
import com.itheima.ydd.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("sys_user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @GetMapping("/list")
    public ResultData list(Integer status,String phone,String login_name, int page, int limit){
        //创建分页构造器,查询系统用户信息
        Page<User> pageInfo = new Page<>(page,limit);
        Page<SysUserInfo> userInfoPage = new Page<>();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(login_name != null,User::getLogin_name,login_name);
        queryWrapper.like(status != null,User::getStatus,status);
        queryWrapper.like(phone != null,User::getPhone,phone);
        queryWrapper.orderByDesc(User::getCreate_date);
        //分页查询
        userService.page(pageInfo,queryWrapper);
        //Copy
        BeanUtils.copyProperties(pageInfo,userInfoPage,"records");
        //遍历集合,添加元素
        List<User> records = pageInfo.getRecords();
        List<SysUserInfo> collect = records.stream().map(item -> {
            SysUserInfo sysUserInfo = new SysUserInfo();
            BeanUtils.copyProperties(item, sysUserInfo);

            //获取角色ID,添加角色信息
            //查询用户角色id集合: role_id
            String[] rowIds = item.getRole_id().replace("[", "")
                    .replace("]", "")
                    .replace("\"", "")
                    .split(",");
            List<String> ids = new ArrayList<>();
            Collections.addAll(ids, rowIds);
            List<Role> roles = roleService.listByIds(ids);
            List<String> strings = roles.stream().map(getRoleName -> {
                String s = getRoleName.getName();
                return s;
            }).collect(Collectors.toList());
            sysUserInfo.setRole_id(ids);
            sysUserInfo.setRolename(strings);
            return sysUserInfo;
        }).collect(Collectors.toList());

        userInfoPage.setRecords(collect);
        // List<SysUserInfo> data = userInfoPage.getRecords();

        return ResultData.ok("", PageResult.init(userInfoPage.getTotal(),userInfoPage.getSize(),userInfoPage.getCurrent(),userInfoPage.getRecords()));
    }
    //用户删除
    @GetMapping("del")
    public ResultData del(String id){
        log.info("用户管理删除:{}",id);
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId,id);
        User one = userService.getOne(updateWrapper);
        Integer status = one.getStatus();
        if (status==1){
            return ResultData.error("删除失败");
        };
        updateWrapper.set(User::getDel_flag,"1");
        userService.update(updateWrapper);
        return ResultData.ok("删除成功","");
    };
    //用户增加
    @PostMapping("add")
    public ResultData add(@RequestBody SysUserInfo sysUserInfo){
        log.info("用户增加:{}",sysUserInfo);
        userService.saveWithRoleId(sysUserInfo);
        return ResultData.ok("用户增加成功","");
    }
    //查询用户详情
    @GetMapping("rowInfo")
    public ResultData rowInfo(String id){
        log.info("查询用户详情:{}",id);
        SysUserInfo userServiceWithId = userService.getWithId(id);
        return ResultData.ok("",userServiceWithId);
    }
    @PostMapping("update")
    public ResultData update(@RequestBody SysUserInfo sysUserInfo){
        log.info("修改用户数据详情:{}",sysUserInfo);
        userService.updateWithSys(sysUserInfo);
        return ResultData.ok("修改数据成功","");
    }
}
